package middleware

import (
	aerrors "UserApp/errors"
	"fmt"
	"github.com/gin-gonic/gin"
	xerrors "github.com/pkg/errors"
)

func ErrorHandle(ctx *gin.Context) {
	//执行业务逻辑
	ctx.Next()
	errInfo, ok := ctx.Get("errors")
	if ok {
		err := errInfo.(error)
		cause := xerrors.Cause(err)
		//如果执行过程中，出现错误
		switch {
		case aerrors.IsNoSqlRow(cause):
			ctx.JSON(200, gin.H{
				"code" : aerrors.Code(cause),
				"reason" : aerrors.Reason(cause),
			})
		case aerrors.IsInternal(cause):
			ctx.JSON(500, gin.H{
				"code" : aerrors.Code(cause),
				"reason" : aerrors.Reason(cause),
			})
		default:
			ctx.JSON(500, gin.H{
				"code" : "",
				"reason" : "unknown",
			})
		}
		//log.Printf("handle request failed, path is %s, reason is %v, stack is %+v", ctx.Request.RequestURI, cause, err)
		fmt.Printf("handle request failed, path is %s, reason is %v, stack is %+v", ctx.Request.RequestURI, cause, err)
	} else {
		fmt.Printf("handle request succeed, path is %s", ctx.Request.RequestURI)
	}
}